/** 
* All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
* 
* PmResourceChangeLineService
* 资源变更明细
* 
* 修改纪录
* 2020-05-15 版本：1.0 shenyouyi 创建。
* @version 版本：1.0
* @author 作者：shenyouyi
* 创建日期：2020-05-15
*/
package com.topscomm.pm.service.impl;

import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.BusinessException;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.pm.pojo.PmResourceApplyLineEntity;
import com.topscomm.pm.pojo.PmResourceChangeLineEntity;
import com.topscomm.pm.service.IPmResourceChangeLineService;
import com.topscomm.pm.service.impl.auto.PmResourceChangeLineServiceAuto;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service(value = "pmResourceChangeLineService")
@Scope(value = "singleton")
public class PmResourceChangeLineService extends PmResourceChangeLineServiceAuto implements IPmResourceChangeLineService {

    /**
     * 重写beforeInsert方法，设置行号
     * @param entity
     * @throws ServiceException
     */
    @Override
    protected void beforeInsert(BasicEntity entity) throws ServiceException {
        super.beforeInsert(entity);
        StringBufferProxy sqlForExists = new StringBufferProxy();
        sqlForExists.appendLineSingle(" pmresourcechangeline.resourcechangeid='{0}'  and exists (select id from pmresourcechange where pmresourcechange.state in (0,1) and pmresourcechange.id = pmresourcechangeline.resourcechangeid )",ConvertUtil.convertToString(entity.getValue("resourcechangeid")));
        List<PmResourceChangeLineEntity> queryByWhere = this.queryByWhere(sqlForExists.toString());
        if (queryByWhere!=null&&queryByWhere.size()>0) {
			throw new BusinessException("其他正在审核或者已开立的变更单中(单据id："+queryByWhere.get(0).getResourcechangeid()+")存在此资源的变更申请，请勿重复变更此资源。");
		}
        String resourcechangeid = entity.getValue("resourcechangeid").toString();
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("resourcechangeid = {0}", resourcechangeid);
        List<String> listFields = new ArrayList<>();
        listFields.add("max(lineno) as maxLineno");
        List<Map<String,Object>> queryResultList = this.queryMapFieldsByWhere(sql.toString(), listFields);
        Long maxLineno = 0L;
        if(queryResultList.size()>0&&queryResultList.get(0)!=null&&queryResultList.get(0).get("maxLineno")!=null){
            maxLineno = Long.valueOf(queryResultList.get(0).get("maxLineno").toString());
        }
        entity.setValue("lineno", maxLineno + 1);
    }
	
}
